<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class Commission extends Model
{

    

    

    // 表名
    protected $name = 'commission';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text',
	    'status_text',
	    'type_text'
    ];
    
	const STATUS_WAIT = 0;
	const STATUS_Y = 1;
	const STATUS_CANCEL = 2;
	
	public static $statusList = [
		self::STATUS_Y => '已发放',
		self::STATUS_WAIT => '待核销',
		self::STATUS_CANCEL => '已取消'
	];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}
	
	const TYPE_SALE = 1;
	const TYPE_GOODS = 2;
	const TYPE_RECOMMEND = 3;
	const TYPE_STOCK = 4;
	
	public static $typeList = [
		self::TYPE_SALE => '推广佣金',
		self::TYPE_GOODS => '提货佣金',
		self::TYPE_RECOMMEND => '推荐奖励',
		self::TYPE_STOCK => '铺货佣金'
	];
	
	public function getTypeTextAttr($value, $data) {
		$value = $value ? : $data['type'];
		$list = self::$typeList;
		return $list[$value] ??'';
	}
	
	
    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function user() {
		return $this->belongsTo('user', 'user_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	public function relationuser() {
		return $this->belongsTo('user', 'relation_user_id',  'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 添加返利记录
	 * @param $userId 用户ID
	 * @param $relationUserId 关联用户ID
	 * @param $orderId 订单ID
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $amount
	 * @param $type
	 * @return false|int
	 */
	public function addRow($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount, $type) {
		$res = Db::name('commission')->insert([
			'user_id' => $userId,
			'relation_user_id' => $relationUserId,
			'order_id' => $orderId,
			'goods_id' => $goodsId,
			'order_goods_id' => $orderGoodsId,
			'amount' => $amount,
			'status' => self::STATUS_WAIT,
			'type' => $type,
			'create_time' => time(),
			'update_time' => time()
		]);
		return $res;
	}
	
	/**
	 * 添加返利记录
	 * @param $userId
	 * @param $relationUserId
	 * @param $orderId
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $amount
	 * @param string $remark
	 * @param $type
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function rebate($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount, $remark = '', $type = self::TYPE_SALE) {
		//记录佣金记录
		$rowRes = $this->addRow($userId, $relationUserId, $orderId, $goodsId, $orderGoodsId, $amount, $type);
		if(!$rowRes) {
			$this->error = '添加佣金记录出错';
			return false;
		}
		return true;
	}
	
	
	/**
	 * 发放佣金
	 */
	public function send($orderId) {
		$this->startTrans();
		try {
			$orderRes = Db::name('order')
				->where(['id' => $orderId])
				->update(['rebate_status' => Order::REBATE_DONE]);
			if($orderRes === false) {
				throw new Exception('更改订单返利状态出错');
			}
			
			$rows = Db::name('commission')
				->where(['order_id' => $orderId, 'status' => self::STATUS_WAIT])
				->select();
			
			if($rows) {
				$fundsModel = new Funds();
				foreach ($rows as $row) {
					$userId = $row['user_id'];
					$type = $row['type'];
					$amount = $row['amount'];
					$user = Db::name('user')->find($userId);
					//添加用户余额
					$userRes = Db::name('user')
						->where(['id' => $userId])
						->setInc('money', $amount);
					if(!$userRes) {
						throw new Exception('添加用户余额出错');
					}
					
					switch ($type) {
						case self::TYPE_SALE:
							$fundsType = $fundsModel::TYPE_REBATE;
							break;
						case self::TYPE_RECOMMEND:
							$fundsType = $fundsModel::TYPE_RECOMMEND;
							break;
						default:
							$fundsType = $fundsModel::TYPE_DESTORY;
					}
					$order = Db::name('order')->find($orderId);
					//添加流水记录
					$fundsRes = $fundsModel->addRecord($userId, $amount, $user['money'], $fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_PLUS, $fundsType, $orderId, '', $order['user_id']);
					if(!$fundsRes) {
						throw new Exception('添加资金记录出错');
					}
				}
				
				$res = Db::name('commission')
					->where(['order_id' => $orderId, 'status' => self::STATUS_WAIT])
					->update(['status' => self::STATUS_Y]);
				if(!$res) {
					throw new Exception('更改佣金记录状态出错');
				}
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
		
		
	}
}
